
import type { Plugin } from 'postcss'
export interface Options {
    viewPortWidth?: number;
    mediaQuery?: boolean;
    unitToConvert?: string;
}
const defaultOptions = {
    viewPortWidth: 750, // 设计稿宽度
    mediaQuery: false,
    unitToConvert: 'px'
}
export const pxToViewport = (options: Options = defaultOptions): Plugin => {
    const opt = Object.assign({}, defaultOptions, options)
    return {
        postcssPlugin: 'postcss-px-to-viewport',
        //css节点都会经过这个钩子
        Declaration(node) {
            const value = node.value
            //匹配到px 转换成vw
            if (value.includes(opt.unitToConvert)) {
                const regexp = new RegExp(`\\d+${opt.unitToConvert}{1}`, 'gi')
                const nodeVal = value.replace(regexp, (match) => {
                    const num = parseFloat(match)
                    const transformValue = Number(((num) / opt.viewPortWidth) * 100)
                    return transformValue.toFixed(4) + 'vw'
                })
                node.value = nodeVal
            }
        },
    }
}

